Page({
    data: {
        list: [],
        checked: false,
        isAllChecked: false,
        totalPrice: 0,
        isEditMode: false, // 编辑模式开关
        settleDisabled: true,
    },

    getList() {
        const token = wx.getStorageSync('token')
        wx.request({
            url: 'http://admin.bsmall.byesame.com/wx/cart/index',
            method: "GET",
            header: {
                'x-byesame-token': token,
            },
            success: (res) => {
                console.log("购物商品", res);
                if (res.data.errno == 0) {
                    let cartList = res.data.data.cartList.map(item => ({
                        ...item,
                        checked: item.checked || false 
                    }));
                    this.setData({
                        list: cartList
                    }, () => {
                        this.checkAllStatus();
                        this.calculateTotal();
                    });
                } else {
                    wx.showToast({
                        title: res.data.errmsg,
                        icon: 'error'
                    });
                }
            },
        })
    },

    // 单个商品选中状态变化
    onChangeItem(event) {
        const index = event.currentTarget.dataset.index;
        const isChecked = event.detail;
        const productId = event.currentTarget.dataset.id;
        const token = wx.getStorageSync('token');
        console.log('单状态:', isChecked);
        // 精准更新当前商品的checked状态（这行是关键，确保组件立即渲染）
        this.setData({
          [`list[${index}].checked`]: isChecked
        }, () => {
          this.checkAllStatus();
          this.calculateTotal();
        });
      
        // 以下接口请求逻辑完全保留，你之前的代码是对的
        wx.request({
          url: 'http://admin.bsmall.byesame.com/wx/cart/checked',
          data: {
            productIds: [parseInt(productId)],
            isChecked: isChecked ? 1 : 0
          },
          method: "POST",
          header: {
            'x-byesame-token': token,
            'content-type': 'application/json'
          },
         
          success: (res) => {
            if (res.data.errno !== 0) {
               
              this.setData({
                [`list[${index}].checked`]: !isChecked
              }, () => {
                this.checkAllStatus();
                this.calculateTotal();
              });
              wx.showToast({ title: res.data.errmsg, icon: 'error' });
            }
          },
          fail: (err) => {
            this.setData({
              [`list[${index}].checked`]: !isChecked
            }, () => {
              this.checkAllStatus();
              this.calculateTotal();
            });
            wx.showToast({ title: '网络错误', icon: 'error' });
          }
        })
      },

    // 全选状态变化
    onChangeAll(event) {
        this.setData({
            checked: event.detail,
        });
        const isAllChecked = event.detail;
        const token = wx.getStorageSync('token');

        console.log('全选状态:', isAllChecked);

        // 获取所有商品的productId
        const productIds = this.data.list.map(item => item.productId);

        // 立即更新UI
        let list = this.data.list.map(item => ({
            ...item,
            checked: isAllChecked
        }));
        this.setData({
            list,
            isAllChecked
        }, () => {
            this.calculateTotal();
        });

        // 发送全选请求到服务器
        wx.request({
            url: 'http://admin.bsmall.byesame.com/wx/cart/checked',
            data: {
                productIds: productIds,
                isChecked: isAllChecked ? 1 : 0
            },
            method: "POST",
            header: {
                'x-byesame-token': token,
                'content-type': 'application/json'
            },
            success: (res) => {
                console.log('全选响应:', res.data);
                if (res.data.errno !== 0) {
                    let list = this.data.list.map(item => ({
                        ...item,
                        checked: !isAllChecked
                    }));
                    this.setData({
                        list,
                        isAllChecked: !isAllChecked
                    }, () => {
                        this.calculateTotal();
                    });
                    wx.showToast({
                        title: res.data.errmsg,
                        icon: 'error'
                    });
                }
            }
        })
    },

    checkAllStatus() {
        const list = this.data.list;
        if (list.length === 0) {
            this.setData({
                isAllChecked: false
            });
            return;
        }
        const isAllChecked = list.every(item => item.checked);
        this.setData({
            isAllChecked
        });
    },

    calculateTotal() {
        const list = this.data.list;
        let total = 0;
        let selectedCount = 0;
        list.forEach(item => {
            if (item.checked) {
                total += item.price * item.number;
                selectedCount++;
            }
        });
        this.setData({
            totalPrice: total * 100,
            settleDisabled: selectedCount === 0
        });
    },

    // 编辑按钮
    bian() {
        wx.showToast({
            title: '编辑功能',
            icon: 'none'
        });
        this.setData({
            isEditMode: !this.data.isEditMode
        });
    },

    // 结算按钮
    handleSettle(e) {
        const {
            list
        } = this.data;

        // 筛选"已选中"商品的productId
        const selectedProductIds = list
            .filter(item => item.checked)
            .map(item => item.productId);

        if (selectedProductIds.length === 0) {
            wx.showToast({
                title: '请选择要结算的商品',
                icon: 'none'
            });
            return;
        }

        console.log('跳转到结算页面的商品ID:', selectedProductIds);

        // 传递选中的商品ID到结算页面
        wx.navigateTo({
            url: `/pages/ShoppingSettle/ShoppingSettle?productIds=${selectedProductIds.join(',')}`,
        });
    },




    // 减少商品数量
minusNum(e) {
    const index = e.currentTarget.dataset.index;
    let list = this.data.list;
    const item = list[index]; // 获取当前商品的完整信息
    if (item.number > 1) { // 数量不能小于1
      item.number--;
      this.setData({
        list
      }, () => {
        this.calculateTotal(); // 更新总价
        // 传递所有必要参数：id、goodsId、productId、number
        this.updateCartNumber(item.id, item.goodsId, item.productId, item.number); 
      });
    }
  },
  
  // 增加商品数量
  plusNum(e) {
    const index = e.currentTarget.dataset.index;
    let list = this.data.list;
    const item = list[index]; // 获取当前商品的完整信息
    item.number++;
    this.setData({
      list
    }, () => {
      this.calculateTotal();
      // 传递所有必要参数：id、goodsId、productId、number
      this.updateCartNumber(item.id, item.goodsId, item.productId, item.number);
    });
  },

   // 调用接口更新购物车数量
updateCartNumber(id, goodsId, productId, number) {
    const token = wx.getStorageSync('token');
    wx.request({
      url: 'http://admin.bsmall.byesame.com/wx/cart/update',
      method: 'POST',
      header: {
        'x-byesame-token': token,
        'content-type': 'application/json'
      },
      // 传递所有接口所需参数
      data: {
        id,
        goodsId,
        productId,
        number
      },
      success: (res) => {
        if (res.data.errno !== 0) {
          wx.showToast({
            title: res.data.errmsg,
            icon: 'error'
          });
        }
      }
    });
  },
    // 单个商品删除


    delItem(e) {
        const index = e.currentTarget.dataset.index;
        const productId = this.data.list[index].productId;
        wx.showModal({
            title: '确认删除',
            content: '确定删除所选商品吗',
            success: (res) => {
                if (res.confirm) {
                    this.delCartItem([productId]); // 调用删除接口
                }
            }
        });
    },



    // 批量删除所选商品
    delSelected() {
        const selectedProductIds = this.data.list
            .filter(item => item.checked)
            .map(item => item.productId);
        if (selectedProductIds.length === 0) {
            wx.showToast({
                title: '请选择要删除的商品',
                icon: 'none'
            });
            return;
        }
        wx.showModal({
            title: '确认删除',
            content: '确定删除所选商品吗',
            success: (res) => {
                if (res.confirm) {
                    this.delCartItem(selectedProductIds);
                }
            }
        });
    },
    // http://admin.bsmall.byesame.com/wx/cart/delete
    // 请求方法:
    // POST
    // productIds: [1]
    // 0: 1
    // 调用删除接口（假设接口为 /wx/cart/delete）
    delCartItem(productIds) {
        const token = wx.getStorageSync('token');
        wx.request({
            url: 'http://admin.bsmall.byesame.com/wx/cart/delete',
            method: 'POST',
            data: {},
            header: {
                'x-byesame-token': token,
                'content-type': 'application/json'
            },
            data: {
                productIds
            },
            success: (res) => {
                if (res.data.errno === 0) {
                    this.getList(); // 删除成功后重新获取购物车列表
                    wx.showToast({
                        title: '删除成功',
                        icon: 'success'
                    });
                } else {
                    wx.showToast({
                        title: res.data.errmsg,
                        icon: 'error'
                    });
                }
            }
        });
    },





    onLoad(options) {
        this.getList()
    }
})1